package com.zbs.framework.dao.security.run;


import com.zbs.framework.dao.permission.entity.Permission;
import com.zbs.framework.dao.permission.service.PermissionService;
import com.zbs.framework.security.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 澎湃新闻启动
 * @author: Zbs
 * @create: 2020-12-01 16:12
 */
@Component
@Slf4j
@Transactional
public class PreAuthorizeApplicationRunner implements CommandLineRunner{
    @Autowired
    private PermissionService permissionService;

    @Override
    public void run(String... args) {
        List<Permission> all = new ArrayList<>();
        SecurityConstants.urlResources.forEach(urlResources -> {
            String[] permission = urlResources.getPermission().split("::");
            all.add(new Permission(permission[0], permission[1],urlResources.getPath()));
        });
        //调用权限服务接口上报配置
        if (!CollectionUtils.isEmpty(all)) {
            new Thread(() -> all.forEach(this::doRetryablePush)).start();
        }

    }

    private void doRetryablePush(Permission permission) {
        try {
            permissionService.save(permission.getServiceName(),permission.getName(),"","",permission.getPath(),true);
        } catch (Exception e) {
            e.printStackTrace();
//            try {
//                Thread.sleep(5000L);
//                doRetryablePush(permission);
//            } catch (InterruptedException ex) {
//                ex.printStackTrace();
//            }
        }
    }

}
